<template>
  <div>
    <!-- 查询条件表单 -->
    <el-form :inline="true" class="mb-4">
      <el-form-item label="编码">
        <el-input
          v-model="query.code"
          style="width: 200px"
          placeholder="请输入编码"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="请选择状态" style="width: 160px" clearable>
          <el-option label="全部" :value="null" />
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="单据日期：">
        <el-date-picker
          v-model="query.dateRange"
          type="daterange"
          range-separator="至"
          :start-placeholder="query.dateRange[0] || '开始'"
          :end-placeholder="query.dateRange[1] || '结束'"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData(1)">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <TestPage
      :table-data="tableData"
      :columns="columns"
      :current-page="pageNo"
      :total="total"
      :page-size="pageSize"
      @page-change="fetchData"
      @action="handleTableAction"
      @edit="openEditDialog"
      @row-audit="openAudit"
    />

    <!-- 审核对话框 -->
    <el-dialog
    v-model="auditVisible"
    title="单据审核"
    width="600px"
    :close-on-click-modal="false"
>
    <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="单据编号：" prop="code">
            <el-input
                v-model="auditForm.code"
                disabled
                placeholder="系统自动填充"
            />
        </el-form-item>

         <el-form-item label="审核人：" prop="auditor">
          <el-select
              v-model="auditForm.auditor"
              placeholder="请选择审核人"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.name} `"
                :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审批意见：" prop="comment">
            <el-input
                v-model="auditForm.comment"
                type="textarea"
                :rows="3"
                placeholder="请输入审批意见"
                maxlength="200"
                show-word-limit
            />
        </el-form-item>
        <el-form-item label="审核结果：" prop="checkResult">
            <el-select
                v-model="auditForm.checkRes"
                placeholder="请选择审核结果"
                style="width: 100%"
            >
                <el-option label="通过" :value="true" />
                <el-option label="不通过" :value="false" />
            </el-select>
        </el-form-item>

    </el-form>

    <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
    </template>
</el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/util/request'
import TestPage from '@/test/TestPage.vue'
import { useRouter } from 'vue-router'
import type { ProDivide } from '@/types/kc/CPCX'
import type { User } from '@/types/rs/User'
import type { OutStoreOrder, outStoreDetail } from '@/types/kc/outStore'
import type { InStoreOrder, InStoreDetail } from '@/types/kc/InStore'

// --- 分页 & 查询 ---
const pageNo = ref(1), pageSize = ref(5), total = ref(0)
const query = reactive<{ code: string; status: number|null; dateRange: [string,string]|[] }>({
  code: '', status: null, dateRange: []
})
const tableData = ref<ProDivide[]>([])

// --- 审核弹窗 ---
// 审核弹窗
const auditVisible = ref(false)
const auditFormRef = ref()
const auditForm = reactive({
  code: '',
  auditor: '',
  comment: '',
  checkRes: null
});
const auditRules = reactive({
  pass: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
})
let current: ProDivide|null = null

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()
let currentRow: ProDivide|null = null

// --- 列定义 ---
const columns = [
  { prop:'id',     label:'ID' },
  { prop:'code',   label:'编码' },
  { prop:'bname',  label:'BOM名称' },
  { prop:'pname',  label:'产品名称' },
  { prop:'count',  label:'数量' },
  { prop:'status', label:'状态' },
  { prop:'date',   label:'日期' },
  { prop:'skname', label:'仓管人' },
  // … 其它字段 …
]

// --- 初始化 ---
onMounted(async () => {
  // 加载用户列表
  const r = await request.post('/per/user/getAll')
  userList.value = r.data.data
  fetchData(1)
})

// --- 工具：格式化日期区间 ---
function fmtDate(d: Date, end=false){
  const z=(n:number)=>n.toString().padStart(2,'0')
  const Y=d.getFullYear(), M=z(d.getMonth()+1), D=z(d.getDate())
  return end?`${Y}-${M}-${D} 23:59:59`:`${Y}-${M}-${D} 00:00:00`
}

// 操作按钮
function handleTableAction(actionName: string) {
  if (actionName === 'add') {
    router.push({ name: 'Addcpcx' })
  }
}


// 编辑 & 删除
const router = useRouter()

function openEditDialog(row: ProDivide) {
  router.push({ name: 'EditCPCX', params: { code: row.code } })
}

// --- 拉取列表 ---
async function fetchData(p: number) {
  const ps = new URLSearchParams()
  ps.append('pageNow', `${p}`)
  ps.append('pageSize', `${pageSize.value}`)
  if (query.code)   ps.append('code', query.code)
  if (query.status!=null) ps.append('status', `${query.status}`)
  if (query.dateRange.length===2) {
    const [s,e] = query.dateRange.map(x=>new Date(x))
    ps.append('startDate', fmtDate(s,false))
    ps.append('endDate',   fmtDate(e,true))
  }
  const res = await request.post('kc/proDivide/getProDividePage', ps)
  const d   = res.data.data
      console.log(d)
  tableData.value = d.list || []
  total.value     = d.total || 0
  pageNo.value    = d.pageNo || p
}

// --- 重置 ---
function reset() {
  query.code = ''
  query.status = null
  query.dateRange = []
  fetchData(1)
}

// --- 打开审核弹窗 ---
function openAudit(row:ProDivide){
  auditForm.code = row.code
  auditVisible.value = true
  console.log('当前审核单据:', row.code)
}

// --- 提交审核 & 生成出入库 ---
async function submitAudit() {
  await auditFormRef.value.validate()
  // 1) 调用审核接口
  await request.post('kc/proDivide/check', {
    code:       auditForm.code,
    typeId:     10,                // 拆卸类型
    status:     3,
    checkManId: auditForm.auditor,  // 绑定审核人ID
      checkComment: auditForm.comment, // 绑定审批意见
      checkRes: auditForm.checkRes // 绑定审核结果 
  })
ElMessage.success('审核完成')
  auditVisible.value=false
  fetchData(pageNo.value)
}


</script>

<style scoped>
.mb-4 { margin-bottom: 16px }
</style>

